package com.ctiot.custom.oauth.api;

import com.ctiot.custom.oauth.constant.OauthConstants;
import com.ctiot.custom.oauth.service.impl.CustomOAuthServiceImpl;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
import org.scribe.utils.OAuthEncoder;

import java.util.UUID;

/**
 * @projectName: oauth-sdk-bim
 * @packageName: com.ctiot.bim.oauth.api
 * @description:
 * @author: huayang.bai
 * @date: 2021-04-12 10:24
 */
public class CustomApi extends DefaultApi20 {

    /**
     * 通过dcoos方式调用接口，sku对应注册应用ID
     */
    private String xAppId;
    /**
     * 通过dcoos方式调用接口，sku对应注册应用密钥
     */
    private String xAppKey;


    /**
     * 三方认证请求地址
     *
     * @param config
     * @return
     */
    @Override
    public String getAuthorizationUrl(OAuthConfig config) {
        return String.format(OauthConstants.AUTHORIZE_URL + "?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&state=%s", config.getApiKey(), OAuthEncoder.encode(config.getCallback()), config.getScope() == null ? "user_info" : config.getScope(), this.generateState());
    }

    /**
     * 获取访问token的url地址
     *
     * @return
     */
    @Override
    public String getAccessTokenEndpoint() {
        return OauthConstants.ACCESS_TOKEN_URL;
    }


    /**
     * 获取访问token的url地址
     *
     * @return
     */
    public String getRefreshTokenEndpoint() {
        return OauthConstants.REFRESH_TOKEN_URL;
    }


    @Override
    public Verb getAccessTokenVerb() {
        return Verb.POST;
    }

    /**
     * 访问token解析器
     *
     * @return
     */
    @Override
    public AccessTokenExtractor getAccessTokenExtractor() {
        // 以json格式解析AccessToken
        return new JsonTokenExtractor();
    }

    /**
     * 获取访问token的url地址
     *
     * @return
     */
    public String getCheckTokenEndpoint() {
        return OauthConstants.CHECK_TOKEN_URL;
    }

    /**
     * 获取用户信息的url地址
     *
     * @return
     */
    public String getUserInfoUrl() {
        return OauthConstants.GET_USER_INFO_URL;
    }

    @Override
    public OAuthService createService(OAuthConfig config) {
        return new CustomOAuthServiceImpl(this, config);
    }

    /**
     * 随机生成状态
     *
     * @return
     */
    private String generateState() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    public String getxAppId() {
        return xAppId;
    }

    public void setxAppId(String xAppId) {
        this.xAppId = xAppId;
    }

    public String getxAppKey() {
        return xAppKey;
    }

    public void setxAppKey(String xAppKey) {
        this.xAppKey = xAppKey;
    }
}
